import "@/styles/im-global.scss";
import '@arco-design/web-vue/dist/arco.css';
import "@/styles/im-ui.scss";
import "@/styles/pageIndex.scss";

// 引入状态管理
import {setupStore} from '@/store';
import {createApp} from "vue";
import router from "./router";
import App from "./App.vue";
import {type QiankunProps, qiankunWindow, renderWithQiankun,} from "vite-plugin-qiankun/dist/helper";
import VueDOMPurifyHTML from 'vue-dompurify-html';
import {websocketStoreWithOut} from '@/store/modules/websocket';
// 自定义防抖、节流指令
import {debounceDirective, throttleDirective} from '@/utils/index.js';
const { wsCache } = useCache();

let app:any; // 这里初始化app, 解决了在unmount卸载当前子应用的问题
const initQianKun = () => {
  renderWithQiankun({
    // bootstrap 只会在微应用初始化的时候调用一次，下次微应用重新进入时会直接调用 mount 钩子，不会再重复触发 bootstrap
    // 通常我们可以在这里做一些全局变量的初始化，比如不会在 unmount 阶段被销毁的应用级别的缓存等
    async bootstrap() {
      // console.log('userInfo====', userInfo);
    },
    // 应用每次进入都会调用 mount 方法，通常我们在这里触发应用的渲染方法，也可以接受主应用传来的参数
    async mount(_props: any) {
      // console.log('菜单===im', router.getRoutes().filter(item => item.meta?.title && item.path !== '/login'));
      // websocketStoreWithOut().connectWebSocket();
      await websocketStoreWithOut().getUserList();
			websocketStoreWithOut().getChatList();
      const params = wsCache.get('userInfo');
      const userInfo = {
        ...params,
        userName: websocketStoreWithOut().imStore.userList?.find(item => item.id === params?.userId)?.nickname
      };
      wsCache.set('userInfo', userInfo);
      render(_props.container);
    },
    // 应用每次 切出/卸载 会调用的unmount方法，通常在这里我们会卸载微应用的应用实例
    unmount(_props: any) {
      if(!window.location.pathname.includes('chatManage')){
        app.unmount();
      }
    },
    update: function (props: QiankunProps): void | Promise<void> {
      // console.log("update");
    },
  });
};

// import createSubAppPinia from '@/utils/pinia';
const render = (container: null) => {
  // 如果是在主应用的环境下就挂载主应用的节点，否则挂载到本地
  const appDom = container ? container : "#app";
  app = createApp(App);
  // const pinia = createSubAppPinia();
  // app.use(pinia);
  setupStore(app);
  app.use(router);
  app.use(VueDOMPurifyHTML);
  app.directive('debounce', debounceDirective); // 自定义防抖指令(监听, 针对Input) <a-input v-model.trim="searchKey" v-debounce="handleDebounce"></a-input>
	app.directive('throttle', throttleDirective); // 自定义节流指令(针对Button的@click事件) <a-button v-throttle="handleThrottle">按钮</a-button>
  app.mount(appDom);
};
// 判断是否为乾坤环境，否则会报错iqiankun]: Target container with #subAppContainerVue3 not existed while subAppVue3 mounting!
qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun() : render(null);
